<template>
  <el-dialog :close-on-click-modal="false" :title="$tt('label_sku_map')" :visible.sync="visible"
    custom-class="dialog_extra" :before-close="beforeCloseFun">
    <div>
      <el-form :model="form" ref="form" label-position="top">
        <el-form-item :label="$tt('label_file_upload')">

          <button_select_file @input="selectFile" type="primary" :disabled="loading" :loading="loading">
            {{ $tt('label_import_excel') }}
            <i class="el-icon-upload2 el-icon--right"></i>
          </button_select_file>
          <el-button @click="downloadXlsx" size="mini" type="primary" :disabled="loading" :loading="loading">{{
            $tt('label_download_import_template') }}<i class="el-icon-download el-icon--right"></i></el-button>
        </el-form-item>
        <el-form-item prop="tableList" :label="$tt('label_sku_list')">
          <ex_super_table ref="table" v-bind="tableBaseOption" :data="form.tableList" height="600">
          </ex_super_table>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog_footer">
        <el-button @click="clickClose" :disabled="stop" :type="loading ? 'warning' : ''">{{ $tt(loading ? 'label_pause' :
          'label_cancel') }}</el-button>
      </span>
    </div>

  </el-dialog>
</template>

<script>
// import XLSX from '@/asset/xlsx.full.min.js'
import ExcelJS from '@/asset/exceljs.bare.min.js'
// import XLSX from 'xlsx-js-style'
import FileSaver from 'file-saver'

const xlsxStructure = {
  skuBarcode: { key: 'skuBarcode', label: 'label_sku_code', index: 1, width: 20, },
  skuCode: { key: 'skuCode', label: 'label_sku_code_cn', index: 2, width: 20, },
  skuName: { key: 'skuName', label: 'label_sku_name', index: 3, width: 20, },
  platformCode: { key: 'platformCode', label: 'label_platform_key', index: 4, width: 20, },
  storeCode: { key: 'storeCode', label: 'label_platform_store', index: 5, width: 20, },
  platformSkuCode: { key: 'platformSkuCode', label: 'label_platform_product_code', index: 6, width: 20, },
}
const mapStatus = {
  'ready': { text: 'label_ready_ing', colorClass: "color_info", },
  'success': { text: 'label_success', colorClass: "color_success", },
  'cover': { text: 'label_update_map', colorClass: "color_success", },
  'fail': { text: 'label_fail', colorClass: "color_danger", },
  'loading': { text: 'label_doing', colorClass: "color_primary", },
}
export default {
  components: {},
  data() {
    return {

      visible: false,
      loading: false,
      stop: false,
      stopCall: false,
      form: {
        tableList: [],
      },

      tableBaseOption: {
        attrs: { 'cell-class-name': this.cellClassName, 'span-method': this.objectSpanMethod },
        model: [
          { key: 'skuBarcode', label: 'label_sku_code', 'min-width': 140, },
          { key: 'skuCode', label: 'label_sku_code_cn', 'width': 140, },
          { key: 'skuName', label: 'label_sku_name', 'min-width': 140, },
          {
            key: 'platformCode', label: 'label_platform_key', 'min-width': 140,
            // 'label-class-name': 'table_header_require',
            // render: (h, { row, column }) => {
            //   const key = column.property
            //   if (row.mapStatus != 'fail') return row[key]
            //   return (<ex_super_input value={row[key]} onInput={e => this.$set(row, key, e)} />)
            // }
          },
          {
            key: 'storeCode', label: 'label_platform_store', 'min-width': 140,
            'label-class-name': 'table_header_require',
            render: (h, { row, column }) => {
              const key = column.property
              if (row.mapStatus != 'fail') return row[key]
              return (<ex_select_auto value={row[key]} onInput={e => this.$set(row, key, e)} class="w_fill"
                items={this.thirdPartyList.filter(it => it.platformCode == (row.platformCode == 'WB' ? 'WILDBERRIES' : row.platformCode))}
                option={{ 'label': "sellerId", 'value': 'sellerId' }}
              />)
            }
          },
          {
            key: 'platformSkuCode', label: 'label_platform_product_code', 'min-width': 140,
            'label-class-name': 'table_header_require',
            render: (h, { row, column }) => {
              const key = column.property
              if (row.mapStatus != 'fail') return row[key]
              return (<ex_super_input value={row[key]} onInput={e => this.$set(row, key, e)} />)
            }
          },
          {
            key: 'mapStatus', label: 'label_map_status', 'width': 120, fixed: "right",
            render: (h, { row }) => {
              const item = mapStatus[row.mapStatus]
              return (<div class={item.colorClass}>{this.$tt(item.text)}</div>)
            }
            // formatter: (r, c, v) => this.$addUnit(v, 'kg'),
          },
          {
            key: 'mapDescription', label: 'label_map_description', 'width': 140, fixed: "right",
            render: (h, { row, column }) => {
              const code = row[column.property]
              if (!code) return this.$tt('data_temp_none')
              return (<text_extra_tooltip_operate
                value={code} ellipsis
                data_type={column.property} data_id={row.id}
              />)
            },
          },
          {
            type: 'operate', width: 160, fixed: "right", operate: [
              {
                if: (row) => row.mapStatus == 'fail' && !this.loading,
                label: 'label_try_map',
                click: (row) => {
                  this.skuMapNet({
                    item: row, tip: true, check: true,
                  })

                }
              },
            ]

          },
        ],
      },

    }
  },
  props: {
    thirdPartyList: {
      type: Array,
      default: () => [],
    }
  },
  methods: {
    clickClose() {
      this.beforeCloseFun(() => {
        this.visible = false
      })
    },
    beforeCloseFun(done) {
      if (this.loading) {
        this.stop = true
        this.stopCall = (resume) => {
          this.loading = false
          this.showEndTip(done, () => {
            this.stop = false
            this.stopCall = false
            resume()
          })
        }
        return
      }
      done()
    },

    skuMapNet({ item, tip, call, check }) {
      // if (check) {
      //   if (!this.$reg.PureNumberLetter(item.storeCode)) {
      //     return this.$message.error(this.$tt(['label_platform_store', 'tip_only_input_number_char']))
      //   }
      // }
      this.$ajax({
        url: "/mms-api/client/SkuPlatformRefClientRpc/checkSkuPlatformRefImport.json",
        method: 'post',
        // type: 'json',
        loading: tip ? this.$tt('tip_submiting') : false,
        data: Object.assign({ isOverride: true }, item),
        success: (res) => {
          if (tip) {
            this.$message.success(this.$tt('tip_operate_success'))
          }

          this.$set(item, 'mapStatus', res.data == true ? 'cover' : 'success')
          this.$set(item, 'mapDescription', "")
        },
        fail: (res) => {
          this.$set(item, 'mapStatus', 'fail')
          this.$set(item, 'mapDescription', res.message)
          if (tip) {
            this.$message.error(res.message)
          }
        },
        complete: () => {
          if (call) call()
        },
      })
    },

    showEndTip(done, fail) {
      const list = this.form.tableList
      const tip = this.$tt(`tip_map_result_show`, {
        sum: list.length,
        ok: list.filter(it => it.mapStatus == 'cover' || it.mapStatus == 'success').length,
        new: list.filter(it => it.mapStatus == 'success').length,
        update: list.filter(it => it.mapStatus == 'cover').length,
        fail: list.filter(it => it.mapStatus == 'fail').length,
      })
      this.$confirm(tip, this.$tt('label_operate_result'), {
        type: 'warning'
      }).then(() => {
        this.stop = false
        this.loading = false
        this.visible = false
        if (done) done()
      }).catch(() => {
        if (fail) fail()

      });
    },


    authListUpload(list, i, vmRowList) {
      this.loading = true
      if (list.length == i) {
        this.loading = false
        return
      }
      this.$set(list[i], 'mapStatus', 'loading')

      this.$nextTick(() => {
        if (vmRowList && vmRowList.length > i) {
          vmRowList[i].scrollIntoView()
        }
      })
      this.skuMapNet({
        item: list[i],
        tip: false,
        call: () => {

          if (this.stop != false && this.stopCall) {

            this.stopCall(() => {
              this.stop = false

              this.authListUpload(list, i + 1,
                this.$refs['table'].$refs['MainTable'].$refs['el-table-ref'].$refs['bodyWrapper'].querySelectorAll('.el-table__body > tbody > tr'))
              if (i + 1 == list.length) {
                this.showEndTip()
              }
            })
            return
          }

          this.authListUpload(list, i + 1,
            this.$refs['table'].$refs['MainTable'].$refs['el-table-ref'].$refs['bodyWrapper'].querySelectorAll('.el-table__body > tbody > tr'))
          if (i + 1 == list.length) {
            this.showEndTip()
          }
        }
      })
    },
    selectFile(e) {
      if (!e || e.length == 0) return
      this.form.tableList = []
      let reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result
        console.log(e.target.result)

        new ExcelJS.Workbook().xlsx.load(data).then(workbook => {
          const worksheet = workbook.getWorksheet(1);
          const list = []
          worksheet.eachRow((row, rowNumber) => {
            if (rowNumber == 1) return
            const out = {}
            Object.values(xlsxStructure).forEach((s) => {
              if (row.values[s.index]) {
                out[s.key] = row.getCell(s.index).text//.values[s.index]
              }
            })
            if (!_.isEmpty(out)) {
              list.push(Object.assign(out, { mapStatus: "ready", }))
            }
          });
          if (list.length == 0) return this.$message.error("导入无数据")
          this.$nextTick(() => {
            this.form.tableList = list
            this.stop = false
            this.stopIndex = false
            this.authListUpload(this.form.tableList, 0,
              this.$refs['table'].$refs['MainTable'].$refs['el-table-ref'].$refs['bodyWrapper'].querySelectorAll('.el-table__body > tbody > tr'))
          })
        })
      };
      reader.readAsArrayBuffer(e[0]);
    },
    downloadXlsx() {



      const wb = new ExcelJS.Workbook()
      const worksheet = wb.addWorksheet(this.$tt('label_sku_map_import_template'))
      worksheet.columns = _.sortBy(Object.values(xlsxStructure), 'index').map(it => {
        if (it.key == 'platformCode') {
          return { header: this.$tt(it.label) + `(${this.$enumOptions['SkuRefPlatformEnum'].join('/')})`, key: it.key, width: it.width }
        }
        return { header: this.$tt(it.label), key: it.key, width: it.width }
      });
      // worksheet.addRow(_.sortBy(Object.values(xlsxStructure), 'index').map(it => this.$tt(it.label)));

      worksheet.getCell('D1').fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFFFFF00' }
      };
      worksheet.getCell('E1').fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFFFFF00' }
      };
      worksheet.getCell('F1').fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFFFFF00' }
      };
      for (let i = 2; i < 102; i++) {
        worksheet.getCell('D' + i).dataValidation = {
          type: 'list',
          allowBlank: true,
          formulae: [`"${this.$enumOptions['SkuRefPlatformEnum'].join(',')}"`]
        };
      }

      // worksheet.addTable({
      //   name: this.$tt('label_sku_map_import_template'),
      //   ref: 'A1',
      //   headerRow: true,
      //   style: {
      //     showFirstColumn: true,
      //     showRowStripes: true,
      //   },
      //   columns: _.sortBy(Object.values(xlsxStructure), 'index').map(it => (
      //     { name: this.$tt(it.label),width:200, filterButton: false }
      //   )),
      //   rows: [],
      // });
      // console.log(worksheet.getCell('D2'))


      wb.xlsx.writeBuffer().then(buffer => {
        FileSaver.saveAs(new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }),  `${this.$tt('label_sku_map_import_template')}${new Date().getTime()}.xlsx`,)

        // this.$downloadBuffer({
        //   buffer,
        //   type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        //   filename: `${this.$tt('label_sku_map_import_template')}${new Date().getTime()}.xlsx`,
        // })
      })


    },

    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (['orderInfo',].includes(column.property)) {
        return "revert_cell_border"
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (['receivingCode', 'customerCode', 'orderInfo', 'orderSku',].includes(column.property)) {
        return { rowspan: row.rowspanOrder, colspan: 1 }
      }

    },
    show() {
      this.form.tableList = []

      this.visible = true

    },




  }
}
</script>
